import random

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

import constants
from constants import image_code_max_time
from libs.captcha.captcha import captcha

from libs.yuntongxun.sms import CCP
from verifications.serializers import RegisterSMSCodeSerializer


# 生成图片验证码
class RegisterImageCodeView(APIView):
    """
    GET  url: /varifications/imagecodes/(?P<image_code_id>.+)/
    前端刷新页面 或 点击验证码图片发送请求， 前段发送验证吗唯一标示（UUID）
    后端生成验证吗并发挥图片，
    图片验证吗用于短信验证码，保存在redis里
    """
    def get(self, request, image_code_id):
        text, image = captcha.generate_captcha()
        # 链接用于存储验证码的reids库
        redis_conn = get_redis_connection('code')
        redis_conn.setex("img_%s"%image_code_id, image_code_max_time, text)

        return HttpResponse(image, content_type='image/jpeg')


# 生成短信验证码
class RegisterSMSCodeView(GenericAPIView):
    """
    GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx&image_code_id=xxxx
    前段点击获取短信验证码，发送请求数据： 手机号， 短信验证码，  唯一标识（短信验证吗的UUID）
    1. 后端验证短信验证吗是否正确，
    2. 后端验证是否在60 秒之内像该号码发送过短信验证码，
    3. 后端生成短信验证码
    4. 保存短信验证码和短信发送记录到redis
    5. 第三方发送短信验证
    """
    serializer_class = RegisterSMSCodeSerializer
    def get(self, requset, mobile):
        serializer = self.get_serializer(data=requset.query_params)
        serializer.is_valid(raise_exception=True)

        # 验证是否在60秒之内发送过验证码
        redis_conn = get_redis_connection('code')
        redis_flag = redis_conn.get('sms_flag_%s'%mobile)
        if redis_flag:
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)
        # 生成验证码
        sms_code = '%06d'%random.randint(0,999999)
        print('sms_code:', sms_code)
        redis_conn.setex('sms_code_%s'%mobile, constants.sms_code_ttl, sms_code)
        redis_conn.setex('sms_flag_%s'%mobile, constants.sms_code_resend_time, 1)
        # 第三方发送短信验证码
        # ccp = CCP()
        # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)

        # celery 异步任务发送， 必须使用 delay调用
        # delay 参数和 任务ide参数是一致的
        # from celery_tasks.sms import tasks
        # tasks.send_sms_code.delay(mobile, sms_code)
        return Response({'message':'ok'})

